package com.example.stock;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

    private ListView lv;
    private ArrayList<holdstock> holdstocklist;
    private MyDatabaseHelper  dbHelper;
    private SQLiteDatabase db;
    private int position=0;//记录列表的滚动位置
    boolean less=true;//默认显示持仓股
    @Override
    protected void onResume() {
        super.onResume();
        lv.setAdapter(null);
        lv.removeAllViewsInLayout();
        revw_data();
        lv.setSelection(position);//恢复列表的滚动位置
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbHelper = new MyDatabaseHelper( this, getExternalFilesDir(null)+"/glodStore.db", null, 1);
        db=dbHelper.getWritableDatabase();
        holdstocklist = new ArrayList<holdstock>();
        /*File src=new File("/data/user/0/com.example.stock/databases/glodStore.db");//私用目录下
        if (true) {
            File dest= new File(getExternalFilesDir(null),"glodStore.db");//公共目录

            try {
                dest.createNewFile();
            } catch (IOException e) {
                //e.printStackTrace();
            }

            FileChannel srcChannel = null;
            FileChannel dstChannel = null;
            try {
                srcChannel = new FileInputStream(src).getChannel();
                dstChannel = new FileOutputStream(dest).getChannel();
                srcChannel.transferTo(0, srcChannel.size(), dstChannel);//复制到公共目录下

                srcChannel.close();
                dstChannel.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        //copyFile(file, AUDIO_FILE_PATH);
        //if(db.isOpen())((TextView)findViewById(R.id.textView2)).setText(dbHelper.getDatabaseName()+"数据库已经打开"+db.getPath());
        new AlertDialog.Builder(this).setTitle(AUDIO_FILE_PATH)//设置对话框标题
                .setMessage(db.getPath())//设置显示的内容
                .setPositiveButton("退出",new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        finish();
                    }
                }).show();//在按键响应事件中显示此对话框*/
        revw_data();
    }
    protected void revw_data(){//更新列表视图数据
        holdstocklist.clear();
        String sqlstr;
        if(less)
            sqlstr="select name,buyprice,sum(number) as number from (select * from stock where sellprice=0 order by buyprice DESC) group by name order by number DESC";
        else
            sqlstr="select name,buyprice,sum(case when sellprice=0 then number else 0 end) as number from (select * from stock order by buyprice DESC) group by name order by number DESC";
        Cursor cursor = db.rawQuery(sqlstr,null);
        while(cursor.moveToNext()){
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String price = Float.toString(cursor.getFloat(cursor.getColumnIndex("buyprice")));
            String num = Integer.toString(cursor.getInt(cursor.getColumnIndex("number")));
            holdstock st = new holdstock(name,price,num);
            holdstocklist.add(st);
        }
        cursor=db.rawQuery("select sum(profit) as profit from stock",null);
        cursor.moveToFirst();
        float sum=cursor.getFloat(0);
        //sum=Math.round(sum*100)/100.0f;//保留两位小数
        this.setTitle("合计盈:"+ Float.toString(sum)+"元");
        lv = (ListView)findViewById(R.id.MyList);

        lv.setOnScrollListener(new AbsListView.OnScrollListener() {

            /**
             * 滚动状态改变时调用
             */
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 不滚动时保存当前滚动到的位置
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    position = lv.getFirstVisiblePosition();
                }
            }

            /**
             * 滚动时调用
             */
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });

        lv.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return holdstocklist.size();
            }
            @Override
            public Object getItem(int position) {
                // return holdstocklist.get(position);
                return null;
            }
            @Override
            public long getItemId(int position) {

                // return position;
                return 0;
            }
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view ;
                if(convertView == null )
                {
                    LayoutInflater inflater = MainActivity.this.getLayoutInflater();
                    view = inflater.inflate(R.layout.list_item,null);
                    //view = View.inflate(getBaseContext(),R.layout.item,null);
                }
                else
                {
                    view = convertView;
                }
                //从studentlist中取出一行数据，position相当于数组下标,可以实现逐行取数据
                holdstock st = holdstocklist.get(position);
                final String sname=st.getName();
                TextView name = (TextView)view.findViewById(R.id.tv_name);
                TextView price  = (TextView)view.findViewById(R.id.tv_price);
                TextView num = (TextView)view.findViewById(R.id.tv_num);
                name.setText(st.getName());
                price.setText("最低价:"+st.getprice()+"元,");
                num.setText("持仓:"+st.getnum()+"股");

                Button btn=(Button)view.findViewById(R.id.Addstock);
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v)
                    {/*需要把btn控件属设android:focusable="false"，这样可以既捕捉onItemClick事件（在非button区域），又可以捕捉onClick等事件*/
                        InputDialog dialog = new InputDialog(MainActivity.this, new InputDialog.OnEditInputFinishedListener(){
                            @Override
                            public void editInputFinished(String name,String price,String num,String buyfee) {

                                String sql="insert into stock(name,buyprice,number,buyfee) values('"+name+"',"+price+","+num+","+buyfee+")";
                                db.execSQL(sql);
                                lv.setAdapter(null);
                                lv.removeAllViewsInLayout();
                                revw_data();
                            }
                        },sname);
                        dialog.setView(new EditText(MainActivity.this));  //若对话框无法弹出输入法，加上这句话
                        dialog.show();
                    }
                });
                return view;
            }
        });/**/
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int postion,long arg3) {
                Bundle bundle = new Bundle();
                bundle.putString("name", holdstocklist.get(postion).getName());
                Intent intent = new Intent();
                intent.putExtras(bundle);
                intent.setClass(MainActivity.this, stocklistActivity.class);
                startActivity(intent);
            }
        });
    }
    public void click(View view) {
        InputDialog dialog = new InputDialog(MainActivity.this, new InputDialog.OnEditInputFinishedListener(){
            @Override
            public void editInputFinished(String name,String price,String num,String buyfee) {

                String sql="insert into stock(name,buyprice,number,buyfee) values('"+name+"',"+price+","+num+","+buyfee+")";
                db.execSQL(sql);
                lv.setAdapter(null);
                lv.removeAllViewsInLayout();
                revw_data();
            }
        },"");
        dialog.setView(new EditText(MainActivity.this));  //若对话框无法弹出输入法，加上这句话
        dialog.show();
    }

    public void dispall(View view) {
        Button btn = (Button)findViewById(R.id.lessbtn);
         if(less){
             less=false;
             btn.setText("显示持仓");
         }
         else
         {
             less=true;
             btn.setText("显示全部");
         }
        lv.setAdapter(null);
        lv.removeAllViewsInLayout();
        position=0;
        revw_data();
    }
}
